package xml;

import model.LevelPack;

import com.thoughtworks.xstream.converters.*;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

/**
 * Defines the process used to convert a LevelPack to and from XML format.
 * 
 * @author Alexander Craig
 */
public class LevelPackConverter implements Converter {

	private static final String LEVEL_XML_TAG = "level";

	@Override
	/**
	 * Defines the process used to export a LevelPack to XML
	 */
	public void marshal(Object source, HierarchicalStreamWriter writer,
			MarshallingContext context) {
		LevelPack pack = (LevelPack) source;
		
		for(int i = 0; i < pack.numLevels(); i++) {
			writer.startNode(LEVEL_XML_TAG);
			writer.setValue(pack.get(i));
			writer.endNode();
		}
	}

	@Override
	/**
	 * Defines the process used to import a LevelPack from XML
	 */
	public Object unmarshal(HierarchicalStreamReader reader,
			UnmarshallingContext context) {
		LevelPack newPack = new LevelPack();
		while(reader.hasMoreChildren()){
			reader.moveDown();
			newPack.addLevel(reader.getValue());
			reader.moveUp();
		}
		return newPack;
	}

	@SuppressWarnings("unchecked")
	@Override
	/**
	 * Used to ensure a LevelPack is being converted.
	 */
	public boolean canConvert(Class type) {
		return type.equals(LevelPack.class);
	}

}
